<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户ID" prop="customerId">
        <el-input
          v-model="queryParams.customerId"
          placeholder="请输入客户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input
          v-model="queryParams.quantity"
          placeholder="请输入数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="添加时间" prop="addTime">
        <el-date-picker clearable
          v-model="queryParams.addTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择添加时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">刷新</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="3">
        <el-button
          type="primary"
          @click="submitOrder"
        >下单 (总价: ¥{{ totalOrderPrice }})</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="cartList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="购物车ID" align="center" prop="cartId" />-->
<!--      <el-table-column label="客户昵称" align="center" prop="userName" />-->
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="总价" align="center" prop="totalPrice" />
      <el-table-column label="添加时间" align="center" prop="addTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.addTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cart:cart:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {listCart, getCart, delCart, addCart, updateCart, placeOrder} from "@/api/cart/cart";

export default {
  name: "Cart",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 购物车表格数据
      cartList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selectedCarts: [],
      totalOrderPrice: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: null,
        productId: null,
        quantity: null,
        addTime: null
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询购物车列表 */
    getList() {
      this.loading = true;
      listCart(this.queryParams).then(response => {
        this.cartList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单刷新
    reset() {
      this.form = {
        cartId: null,
        customerId: null,
        productId: null,
        quantity: null,
        addTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 刷新按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedCarts = selection;
      this.totalOrderPrice = selection.reduce((total, item) => total + item.totalPrice, 0);
    },
    submitOrder() {
      if (this.selectedCarts.length === 0) {
        this.$message.error('请选择要下单的商品');
        return;
      }

      // 提取购物车项的 ID
      const cartIds = this.selectedCarts.map(item => item.cartId);

      // 发送下单请求
      placeOrder(cartIds).then(response => {
        console.log("下单成功：", response);
        // 可以在这里执行一些后续操作，比如清空选中的购物车项
        this.selectedCarts = [];
        this.totalOrderPrice = 0;
        // 刷新购物车列表
        this.getList();
        this.$message({
          message: '商品已成功下单',
          type: 'success'
        });
      }).catch(error => {
        console.error("下单失败：", error);
      });
    },
    /** 删除购物车条目 */
    handleDelete(row) {
      this.$confirm('确定要删除这个购物车条目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCart(row.cartId).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList(); // 刷新购物车列表
        }).catch(error => {
          this.$message.error('删除失败: ' + error);
        });
      }).catch(() => {
        // 取消删除操作
      });
    },
  }
};
</script>
